<!--
 * @Description: 
 * @Author: ldx
 * @Date: 2023-03-02 21:05:41
 * @LastEditors: ldx
 * @LastEditTime: 2023-04-28 15:12:59
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <script id="vertex" type="x-shader/x-vertex">
    attribute vec4 a_Position;
    attribute vec2 a_Pin;
    varying vec2 v_Pin;
    void main(){
      // 顶点位置
      gl_Position = a_Position;
      v_Pin = a_Pin;
    }
  </script>
  <script id="fragment" type="x-shader/x-fragment">
    precision mediump float;
    uniform sampler2D u_Sampler;
    uniform sampler2D u_Pattern;
    uniform sampler2D u_Mask;
    varying vec2 v_Pin;
    void main(){
      vec4 o=texture2D(u_Sampler,v_Pin);
      vec4 p=texture2D(u_Pattern,v_Pin);
      vec4 m=texture2D(u_Mask,v_Pin);
      vec4 p2=vec4(1,1,1,1);
      if(m.x > 0.5){
        p2 = mix(o,p,0.5);
      }
      gl_FragColor=p2*o;
    }
  </script>
  <canvas id="canvas"></canvas>
  <script type="module">
    import { initProgram, getViewMatrix, imgPromise } from '../jsm/utils.js'
    import Poly from '../jsm/Poly.js'
    import { Matrix4, Vector3, Quaternion } from 'https://unpkg.com/three/build/three.module.js';
    const canvas = document.querySelector('#canvas')
    // 设置canvas容器的宽高
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    // 获取webgl上下文
    const gl = canvas.getContext('webgl');
    // 声明将来用来清空绘图区的颜色。分别对应r,g,b,a
    gl.clearColor(0, 0, 0, 1)
    // 使用之前声明的颜色，清空绘图区
    gl.clear(gl.COLOR_BUFFER_BIT)

    // 初始化程序对象
    initProgram(gl)

    const vertices = new Float32Array([
      -0.2,0.4,0, 0,1,
      -0.2,-0.4,0, 0,0,
      0.2,0.4,0,  1,1,
      0.2,-0.4,0,  1,0
    ])

    const img1 = new Image()
    img1.src = './images/dress.jpg'
    const img2 = new Image()
    img2.src = './images/pattern1.jpg'
    const img3 = new Image()
    img3.src = './images/mask-dress.jpg'

    const rect = new Poly({
      gl,
      source:vertices,
      type: 'TRIANGLE_STRIP',
      attributes: {
        a_Position: {
          size: 3,
          index: 0
        },
        a_Pin: {
          size: 2,
          index: 3
        },
      }
    })
   Promise.all([
      imgPromise(img1),
      imgPromise(img2),
      imgPromise(img3),
    ]).then(() => {
      rect.maps = {
        u_Sampler: { image: img1 },
        u_Pattern: { image: img2 },
        u_Mask: { image: img3 },
      }
      rect.updateMaps()
      render()
    })

    //渲染
    function render() {
      gl.clear(gl.COLOR_BUFFER_BIT);
      rect.draw()
    }
   
    
  </script>
</body>

</html>